<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\admin\model\user\Finance;
use app\common\api\controller\Relation;
use app\common\model\Member;
use app\common\model\MemberFinance;
use think\Db;
use think\Request;
use app\common\controller\Api;
use think\Validate;

class Invest extends Api
{
    protected static $model = null;
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\admin\model\user\Invest();
    }

    /**
     * 投资列表
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $pageSize = input('page_size', 15);
        $userId = $this->auth->id;
        $list = self::$model
            ->where('user_id', $userId)
            ->order('id desc')
            ->paginate($pageSize);

        $this->success('投资列表', $list);
    }

    /**
     * 复投
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reinvest()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数缺失！');
        }

        $row = self::$model->find($id);
        if (!$row) {
            $this->error('该投资不存在！');
        }

        if ($row->status != 1) {
            $this->error('该投资不可复投！');
        }

        $row->total_days = 0;
        $row->num += 1;
        $row->status = 0;
        $res = $row->save();
        if (!$res) {
            $this->error('复投失败！');
        }
        $this->success('复投成功！');
    }

    /**
     * 申请兑换
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tf()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数缺失！');
        }

        $row = self::$model->find($id);
        if (!$row) {
            $this->error('该投资不存在！');
        }

        if (!in_array($row->status, [1, 5])) {
            $this->error('该投资不可兑换！');
        }

        $row->status = 2;
        $res = $row->save();
        if (!$res) {
            $this->error('兑换申请失败！');
        }
        $this->success('兑换申请成功！');
    }
}